package com.ljx.video.util;

import cn.hutool.core.util.StrUtil;
import com.ljx.video.domain.vo.req.FileUploadReq;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2025-01-30  20:40
 */
@Component
public class LocalUtil {

    public static String MAIN_PATH = System.getProperty("user.dir");

    public void uploadChunkToLocal(FileUploadReq req) {
        try {
            String mainPath = MAIN_PATH + "/file/" + req.getFileMd5();
            File file = new File(mainPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            req.getFile().transferTo(new File(mainPath + "/" + req.getChunk()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void mergeChunksFromLocal(FileUploadReq req) {
       try {
           List<String> chunksPath = new ArrayList<>();
           for(int i = 0; i < req.getTotalChunk(); i++) {
               chunksPath.add(new String(MAIN_PATH + "/file/" + req.getFileMd5() + "/" + i));
           }

           String file = MAIN_PATH + "/file/" + req.getFileMd5() + "/" + req.getFilename();
           Path outputPath = Paths.get(file);

           // 确保目标文件存在，如果不存在就创建
           if (Files.notExists(outputPath)) {
               Files.createFile(outputPath);
           }

           try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
               byte[] buffer = new byte[8192];  // 设置缓冲区大小
               for (String inputFile : chunksPath) {
                   try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile))) {
                       int bytesRead;
                       while ((bytesRead = in.read(buffer)) != -1) {
                           out.write(buffer, 0, bytesRead);
                       }
                   }
               }
           }

           clearChunks(chunksPath);
       } catch (Exception e) {
           e.printStackTrace();
       }
    }

    private void clearChunks(List<String> chunksPath) throws IOException {
        for (String chunk : chunksPath) {
            Files.deleteIfExists(Paths.get(chunk));
        }
    }

    public InputStream download(String fileMd5, String tsNum) {
        try {
            if (StrUtil.isEmpty(tsNum)) {
                return Files.newInputStream(Paths.get(MAIN_PATH + "/file/" + fileMd5 + "/index.m3u8"));
            }
            return Files.newInputStream(Paths.get(MAIN_PATH + "/file/" + fileMd5 + "/ts/" + tsNum));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
